package com.ykdl.member.kid.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import net.wxxr.dataparse.model.DataParseError;
import net.wxxr.dataparse.model.DataState;
import net.wxxr.http.interfaces.ITag;
import net.wxxr.http.request.HttpBaseRequest;

import com.lidroid.xutils.BitmapUtils;
import com.ykdl.member.constant.KidConfig;
import com.ykdl.member.kid.R;
import com.ykdl.member.kid.beans.GroupsBean;
import com.ykdl.member.kid.beans.HomeMessageCount;
import com.ykdl.member.kid.beans.Listinfobean;
import com.ykdl.member.kid.circle.AllCircleActivity;
import com.ykdl.member.kid.circle.CircleTopicActivity;
import com.ykdl.member.kid.image.ImageLoader;
import com.ykdl.member.kid.messagebox.MyMessageAcivity;
import com.ykdl.member.kid.prefs.CircleReadPrefs;
import com.ykdl.member.kid.util.AccessTokenKeeper;
import com.ykdl.member.kid.util.RequestAsAccessTokenUtil;
import com.ykdl.member.kid.widget.AsyncImageView;
import com.ykdl.member.kid.widget.RefreshListView;
import com.ykdl.member.kid.widget.RefreshListView.OnRefreshListener;
import com.ykdl.member.views.IaskMenuBarView;
import com.ykdl.net.manager.TaskManager;
import com.ykdl.net.manager.Wxxr;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

public class MyCircleFragment extends BaseFragment_home {
	private ArrayList<Listinfobean> mygroup_list;
	private RefreshListView mygroup_listview;
	private MyCircleAdapter adapter;
	private int start_id = 0;
	private int cursor = 0;
	private int count = 20;
	private BitmapUtils bitmapUtil;
	private HomeMessageCount messageCountBean;
	private HttpBaseRequest request;
	private CircleReadPrefs circlereadState;
	private boolean isChange = false;
	private TextView tv_right,tv_left;
	

	@Override
	public View initView(LayoutInflater inflater) {
		/*setTopTitle("我的圈子", R.string.all_circle, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						AllCircleActivity.class);
				startActivityForResult(intent, 0);
			}
		}, R.string.message, 0, new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						MyMessageAcivity.class);
				startActivity(intent);
			}
		}, R.drawable.title_bg, false);*/
		view = inflater.inflate(R.layout.mycircleactivity_xml, null);
		bitmapUtil = new BitmapUtils(getActivity());
		circlereadState = new CircleReadPrefs(mContext);
		circlereadState.clearData();
		mygroup_listview = (RefreshListView) view.findViewById(
				R.id.mygroup_listview);
//		iask_menu_bar = (IaskMenuBarView) getActivity().findViewById(
//				R.id.iask_menu_bar);
//		iask_menu_bar.setSelectedID(R.id.bar_mycircle);
//		iask_menu_bar.setBaseScreen(getActivity());
		tv_left=(TextView) view.findViewById(R.id.left_bt);
		tv_right=(TextView) view.findViewById(R.id.right_bt);
		tv_left.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						AllCircleActivity.class);
				startActivityForResult(intent, 0);
			}
		});
		tv_right.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(getActivity(),
						MyMessageAcivity.class);
				startActivity(intent);
			}
		});
		mygroup_listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Listinfobean bean = (Listinfobean) adapter.getItem(arg2);
				goGroup(bean);
			}
		});
		mygroup_listview.setMoreClick(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				inint();
			}
		});
		mygroup_listview.setonRefreshListener(new OnRefreshListener() {

			@Override
			public void onRefresh() {
				// TODO Auto-generated method stub
				cursor = 0;
				inint();
			}
		});
//		initMessageCount();
		inint();
		return view;
	}


	@Override
	public void initData(Bundle savedInstanceState) {

	}

	class MyCircleAdapter extends BaseAdapter {

		ArrayList<Listinfobean> list;

		public void setList(ArrayList<Listinfobean> list) {
			this.list = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			if (list == null) {
				return 0;
			} else {
				return list.size();
			}

		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return list.get(position - 1);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHolder holder = null;
			if (convertView == null) {
				convertView = RelativeLayout.inflate(mContext,
						R.layout.mycircle_item, null);
				holder = new ViewHolder();
				holder.head = (AsyncImageView) convertView
						.findViewById(R.id.head);
				holder.group_name = (TextView) convertView
						.findViewById(R.id.group_name);
				holder.personnum = (TextView) convertView
						.findViewById(R.id.personnum);
				holder.notice_coment = (TextView) convertView
						.findViewById(R.id.notice_coment);
				holder.signin = (ImageView) convertView
						.findViewById(R.id.signin);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			bitmapUtil.configDefaultLoadingImage(R.drawable.circle_default);
			bitmapUtil.configDefaultLoadFailedImage(R.drawable.circle_default);
			if (list.get(position).getIcon_file_meta() != null) {
				String url = list.get(position).getIcon_file_meta()
						.getDownload_urls().getBig().getUrl();
				bitmapUtil.display(holder.head, url);
			} else {
				holder.head.setDefaultDrawable(getResources().getDrawable(
						R.drawable.circle_default));
			}
			holder.group_name.setText(list.get(position).getGroup_name());
			if (!isChange) {
				if (list.get(position).getNew_topics_count() == 0) {
					holder.personnum.setVisibility(View.GONE);
				} else {
					holder.personnum.setVisibility(View.VISIBLE);
					holder.personnum.setText(list.get(position)
							.getNew_topics_count() + "");
				}

			} else {
				if ("true".equals(circlereadState.getCircleState(list.get(
						position).getGroup_id()
						+ ""))) {
					holder.personnum.setVisibility(View.GONE);
				} else {
					if (list.get(position).getNew_topics_count() == 0) {
						holder.personnum.setVisibility(View.GONE);
					} else {
						holder.personnum.setVisibility(View.VISIBLE);
						holder.personnum.setText(list.get(position)
								.getNew_topics_count() + "");
					}
				}
			}

			if (list.get(position).getLatest_topics() != null) {
				holder.notice_coment.setText(list.get(position)
						.getLatest_topics().get(0).getTitle());
			}
			if (list.get(position).isIs_registration()) {
				holder.signin.setVisibility(View.VISIBLE);
			} else {
				holder.signin.setVisibility(View.GONE);
			}
			return convertView;
		}

	}

	class ViewHolder {
		AsyncImageView head;
		ImageView signin;
		TextView group_name;
		TextView personnum;
		TextView notice_coment;
	}

	public void goGroup(Listinfobean bean) {
		Intent intent = new Intent(mContext, CircleTopicActivity.class);
		intent.putExtra("bean", bean);
		intent.putExtra("group_id", bean.getGroup_id() + "");
		circlereadState.setCircleState(bean.getGroup_id() + "", "true");
		startActivityForResult(intent, 0);
	}

	private void inint() {
//		showProgress("正在加载中,请稍等...");
		String pageurl = KidConfig.GET_MY_GROUPS;
		Map<String, String> map = new HashMap<String, String>();
		map.put("start_id", String.valueOf(start_id));
		map.put("cursor", String.valueOf(cursor));
		map.put("count", String.valueOf(count));
		HttpBaseRequest request = Wxxr.getInstance().getRequest(pageurl, map,
				null);
		TaskManager.startHttpRequest(request, new getgroupTag(),
				GroupsBean.class);

	}

	class getgroupTag implements ITag {

		@Override
		public void refreshUI(Object t, DataState ds) {
			// TODO Auto-generated method stub
			if (t instanceof GroupsBean) {
				finishProgress();
				GroupsBean bean = (GroupsBean) t;
				mygroup_list = bean.getList();
				adapter = new MyCircleAdapter();
				adapter.setList(mygroup_list);
				adapter.notifyDataSetChanged();
				if (bean.getNext_cursor() == bean.getTotal_number()) {
					mygroup_listview.setMoreButtoIsGon(true);
				} else {
					mygroup_listview.setMoreButtoIsGon(false);
					cursor = bean.getNext_cursor();
				}
				mygroup_listview.onRefreshComplete();
				mygroup_listview.setFecthMoreOk();
				mygroup_listview.setAdapter(adapter);
				Log.e("alan", "-------t:" + t.toString());

			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}
	}

	private void initMessageCount() {
		AccessTokenKeeper keeper = new AccessTokenKeeper(getActivity());
		if (keeper.getmisAnonymous())
			return;
		String url = KidConfig.BASE_TEST_SERVER + "pages/inbox";
		request = Wxxr.getInstance().getRequest(url, null);
		TaskManager.startHttpRequest(request, new getMessageCountTag(),
				HomeMessageCount.class);
	}

	class getMessageCountTag implements ITag {
		@Override
		public void refreshUI(Object t, DataState ds) {
			if (null != t && t instanceof HomeMessageCount) {
				messageCountBean = (HomeMessageCount) t;
				if (messageCountBean.isExpired()) {
					RequestAsAccessTokenUtil.getInstance(mContext)
							.refreshTokenRequest(request, this,
									HomeMessageCount.class);
				} else {
					settingMessageCount();
				}

			}
		}

		@Override
		public boolean refreshError(DataParseError parseError) {
			return true;
		}

		@Override
		public void refreshCancel() {
		}

	}

	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		if (resultCode==-1) {
			start_id = 0;
			 cursor = 0;
			count = 20;
			inint();
		}
		isChange = true;
		adapter.notifyDataSetChanged();
		mygroup_listview.setAdapter(adapter);
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	/*@Override
	public void onResume() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().setCurrentActivity(TAG);
//		start_id = 0;
//		 cursor = 0;
//		count = 20;
//		inint();
		super.onResume();
	}
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		ImageLoader.getInstance().pause(TAG);
		super.onPause();
	}*/
	
	public void settingMessageCount() {
		/*
		 * if (messageCountBean.getNew_messages_count() > 0 ||
		 * messageCountBean.getNotification_count() > 0) { if
		 * (messageCountBean.getNew_messages_count() > 0){
		 * MyPrefs.setChatLetterCount(this, "1");
		 * iask_menu_bar.setMessageBar(true); }else {
		 * MyPrefs.setChatLetterCount(this, null);
		 * iask_menu_bar.setMessageBar(false); }
		 * 
		 * if (messageCountBean.getNotification_count() > 0) {
		 * iask_menu_bar.setMessageBar(true); MyPrefs.setMessageCount(this,
		 * "1"); }else { iask_menu_bar.setMessageBar(false);
		 * MyPrefs.setMessageCount(this, null); } }else {
		 * iask_menu_bar.setMessageNoBar(); MyPrefs.setMessageCount(this, null);
		 * MyPrefs.setChatLetterCount(this, null); }
		 */
	}
}